package com.easy.dn.ui.main.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easy.common.base.BaseActivity;
import com.easy.common.baserx.RxBus;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.dn.app.AppConstant;
import com.easy.dn.bean.ListBean;
import com.easy.dn.bean.PinnedHeaderBean;
import com.easy.dn.bean.ProfessionTypeBean;
import com.easy.dn.ui.main.adapter.BaseHeaderAdapter;
import com.easy.dn.ui.main.adapter.ProfessionTypeAdapter;
import com.easy.dn.ui.main.contract.ProfessionTypeContract;
import com.easy.dn.ui.main.model.ProfessionTypeModel;
import com.easy.dn.ui.main.presenter.ProfessionTypePresenter;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.SerializableMap;
import com.easy.dn.widget.ClearEditText;
import com.oushangfeng.pinnedsectionitemdecoration.PinnedHeaderItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import dn.easy.com.easyto.R;


/**
 * 行业类别
 * 代码有毒 等待净化 --。
 */
public class ProfessionTypeActivity extends BaseActivity<ProfessionTypePresenter, ProfessionTypeModel> implements ProfessionTypeContract.View, DnToolbar.OnRightTitleClickListener {

    @Bind(R.id.recyclerview)
    RecyclerView mRecyclerview;
    @Bind(R.id.select_number)
    TextView mSelectNumber;
    @Bind(R.id.check_gone)
    CheckBox mCheckGone;
    @Bind(R.id.linear_viewOrGone)
    LinearLayout mLinearViewOrGone;
    @Bind(R.id.clearEditText)
    ClearEditText mClearEditText;
    @Bind(R.id.recy_top_select)
    RecyclerView mRecyTopSelect;

    private ListBean allData = new ListBean();
    private Map<String, ProfessionTypeBean> mSelect; // 选中的数据
    private String mIsWhere;
    private SerializableMap mSerializableMap = new SerializableMap();
    private SerializableMap mSeletData;
    private Map<String, Map<String, ProfessionTypeBean>> mselectProfessionDa;
    private int mMaxNum;
    private LinearLayoutManager mLayoutManager;
    private List<PinnedHeaderBean<ProfessionTypeBean>> mData;
    private BaseHeaderAdapter mAdapter;
    private ProfessionTypeAdapter mTypeAdapter;
    private List<String> mList;
    private List<String> mTopSelectList;

    @Override
    public int getLayoutId() {
        return R.layout.act_profession_type;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        initTitle();
        mToolbar.setMainTitle(R.string.search_trade);
        mToolbar.setOnRightTitleClickListener(this);
        mToolbar.setMainTitleRightText(R.string.save);
        Bundle bundle = getIntent().getExtras();
        mIsWhere = bundle.getString(AppConstant.PROFESSIONTYPE);
        mMaxNum = bundle.getInt("maxNum");
        mSelectNumber.setText(getString(R.string.limit_profession) + 0 + "/" + mMaxNum);
        mSeletData = (SerializableMap) bundle.getSerializable("map");
        if (mSeletData != null) {
            mselectProfessionDa = mSeletData.getMap();
            mSelect = mselectProfessionDa.get(mIsWhere);
        } else {
            mSelect = new HashMap<>();
        }
        mSelectNumber.setText(getString(R.string.limit_profession) + mSelect.size() + "/" + mMaxNum);
        initTopSelectData();
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerview.setLayoutManager(mLayoutManager);
        mPresenter.getData(mSelect);
        loadListener();
    }

    /**
     * 初始化 已经选择的上个界面
     */
    private void initTopSelectData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyTopSelect.setLayoutManager(layoutManager);
        mTopSelectList = new ArrayList<>();
        for (String selectName : mSelect.keySet()) {
            mTopSelectList.add(selectName);
        }
        mTypeAdapter = new ProfessionTypeAdapter(R.layout.item_top_select, mTopSelectList);
        mRecyTopSelect.setAdapter(mTypeAdapter);
        mTypeAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                // 去掉选择的行业
                ProfessionTypeBean bean = mSelect.get(mTopSelectList.get(position));
                bean.setIsChecked(false);
                mSelect.remove(mTopSelectList.get(position));
                mAdapter.notifyDataSetChanged();
                changeTopList();
            }
        });
    }

    @Override
    public void returnProfessionList(ListBean allData) {
        this.allData = allData;
        mData = allData.getData();
        init();
    }

    @Override
    public void returnSelectProfessionList(ListBean listBean) {
        List<PinnedHeaderBean<ProfessionTypeBean>> data = listBean.getData();
        mAdapter.setNewData(data);
    }

    private void init() {
        mAdapter = new BaseHeaderAdapter<PinnedHeaderBean<ProfessionTypeBean>>(mData) {
            @Override
            protected void addItemTypes() {
                addItemType(BaseHeaderAdapter.TYPE_HEADER, R.layout.item_header);
                addItemType(BaseHeaderAdapter.TYPE_DATA, R.layout.item_profession);
            }

            @Override
            protected void convert(BaseViewHolder holder, PinnedHeaderBean<ProfessionTypeBean> item) {
                switch (holder.getItemViewType()) {
                    case BaseHeaderAdapter.TYPE_HEADER:
                        int i = holder.getLayoutPosition();
                        holder.setText(R.id.tvHeader, item.getPinnedHeaderName());
                        break;
                    case BaseHeaderAdapter.TYPE_DATA:
//                        int position = holder.getLayoutPosition();
                        holder.setText(R.id.title, item.getData().getTradeTypeName() + "");
                        holder.setChecked(R.id.title_check, item.getData().isChecked());
                        break;
                }
            }
        };
        mRecyclerview.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (mAdapter.getItemViewType(position)) {
                    case BaseHeaderAdapter.TYPE_DATA:
                        PinnedHeaderBean<ProfessionTypeBean> bean = (PinnedHeaderBean<ProfessionTypeBean>) mAdapter.getData().get(position);
                        ProfessionTypeBean professionTypeBean = bean.getData();
                        CheckBox checkBox = (CheckBox) view.findViewById(R.id.title_check);
                        if (checkBox.isChecked()) {
                            professionTypeBean.setIsChecked(false);
                            checkBox.setChecked(false);
                            mSelect.remove(professionTypeBean.getTradeTypeName());
                            changeTopList();
                        } else {
                            if (mSelect.size() < mMaxNum) {
                                professionTypeBean.setIsChecked(true);
                                checkBox.setChecked(true);
                                mSelect.put(professionTypeBean.getTradeTypeName(), professionTypeBean);
                                changeTopList();
                            } else {
                                DnUtils.showToast(mClearEditText, ProfessionTypeActivity.this.getResources().getString(R.string.noChoose));
                            }
                        }
                        break;
                    case BaseHeaderAdapter.TYPE_HEADER:
                        break;
                }
            }

        });
        mRecyclerview.addItemDecoration(new PinnedHeaderItemDecoration.Builder(BaseHeaderAdapter.TYPE_HEADER).enableDivider(false).disableHeaderClick(true).create());
        mRecyclerview.setAdapter(mAdapter);
    }

    /**
     * 更改顶层选中的状态
     */
    private void changeTopList() {
        mList = new ArrayList<>();
        for (String selectName : mSelect.keySet()) {
            mList.add(selectName);
        }
        mTopSelectList = mList;
        mSelectNumber.setText(getString(R.string.limit_profession) + mSelect.size() + "/" + mMaxNum);
        mTypeAdapter.setNewData(mTopSelectList);
    }

    @Override
    public void onRightClick(View view) {
        mselectProfessionDa = new HashMap<>();
        mselectProfessionDa.put(mIsWhere, mSelect);
        mSerializableMap.setMap(mselectProfessionDa);
        RxBus.getInstance().post(AppConstant.PROFESSIONTYPE, mSerializableMap);
        finish();
    }

    private void loadListener() {
        //展开
        mCheckGone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCheckGone.setText(getResources().getString(R.string.selected_close));
                    mLinearViewOrGone.setVisibility(View.VISIBLE);
                } else {
                    mCheckGone.setText(getResources().getString(R.string.selected_open));
                    mLinearViewOrGone.setVisibility(View.GONE);
                }
            }
        });

        //过滤关键字 搜索功能
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                filterData(charSequence.toString());
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    private void filterData(String filterStr) {
        if (filterStr == null || filterStr.equals("")) {
            mAdapter.setNewData(mData);
        }else {
            mPresenter.getSelectData(mSelect,filterStr);
        }
    }

    @Override
    public void showLoading(String title) {
    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {

    }
}
